package com.iot.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iot.commonutils.utils.JwtUtil;
import com.iot.commonutils.utils.Result;
import com.iot.user.dtos.UserDto;
import com.iot.user.entity.User;
import com.iot.user.mapper.UserMapper;
import com.iot.user.service.UserLoginService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserLoginServiceImpl extends ServiceImpl<UserMapper, User> implements UserLoginService {
    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Override
    public Result login(UserDto dto) {
        if (StringUtils.isEmpty(dto.getUsername()) && StringUtils.isEmpty(dto.getPassword())) {
            return Result.error("用户名或密码不能为空");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        QueryWrapper<User> name = queryWrapper.eq("name", dto.getUsername());
        List<User> listUser = list(name);
        if (listUser != null && listUser.size() == 1) {
            User user = listUser.get(0);
            String md5DigestAsHex = DigestUtils.md5DigestAsHex((dto.getPassword() + user.getSalt()).getBytes());
            if (user.getPassword().equals(md5DigestAsHex)) {
                user.setPassword("");
                user.setSalt("");
                user.setLoginTime(new Date());
                //更新登录时间
                UpdateWrapper<User> wrapper = new UpdateWrapper<>();
                wrapper.eq("id", user.getId());
                User user1 = new User();
                user1.setLoginTime(user.getLoginTime());
                update(user1, wrapper);
                //包装数据给前端
                Map<String, Object> map = new HashMap();
                map.put("token", JwtUtil.getToken(new Long(user.getId())));
                map.put("user", user);
                //把用户id和token放入redis中
                redisTemplate.opsForValue().set("USER_ID", user.getId());
                redisTemplate.opsForValue().set("NAME", user.getName());
                redisTemplate.opsForValue().set("TOKEN", JwtUtil.getToken(new Long(user.getId())));
                return Result.success("用户登录成功", map);

            } else {
                return Result.error("密码错误！请重试！");
            }
        } else {
            return Result.error("用户不存在");

        }
    }
}
